package com.gx.smart.building.ui.common.fragment;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ToastUtils;
import com.gx.smart.base.BaseMVVMFragmentV2;
import com.gx.smart.base.BaseViewModel;
import com.shuyu.waveview.AudioPlayer;

/**
 * @author: xiaosy
 * 时间: 2022/6/17
 * @Description: java类作用描述
 * @Version: 1.0
 **/
public abstract class BaseMVVMFragmentAudioV2<VM extends BaseViewModel> extends BaseMVVMFragmentV2<VM> implements Handler.Callback {
    protected com.shuyu.waveview.AudioPlayer audioPlayer;
    protected Handler mRemoteHandler;

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        switch (msg.what) {
            case AudioPlayer.HANDLER_COMPLETE:
                playComplete();
                break;
            case AudioPlayer.HANDLER_ERROR:
                ToastUtils.showLong("播放发生错误");
                if (audioPlayer != null) {
                    audioPlayer.pause();
                }
                break;
        }
        return false;
    }

    protected abstract void playComplete();

    protected void initAudioPlayer() {
        mRemoteHandler = new Handler(this);
        audioPlayer = new AudioPlayer(requireContext(), mRemoteHandler);
    }

    /**
     * 播放
     */
    public void audioPlay(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            ToastUtils.showLong("文件不存在");
            return;
        }
        if (audioPlayer != null) {
            audioPlayer.playUrl(filePath);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        audioPlayPause();
    }


    /**
     * 暂停
     */
    public void audioPlayPause() {
        if (audioPlayer != null) {
            audioPlayer.pause();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (audioPlayer != null) {
            audioPlayer.stop();
        }
        if (mRemoteHandler != null) {
            mRemoteHandler.removeCallbacksAndMessages(null);
        }
    }
}
